<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
		// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
		),
		// page action renders "static" pages stored under 'protected/views/site/pages'
		// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
		),
		);
	}

	public function actionImage($str){
		$info = new Info();
		$str = $info->decrypt($str);
		$img = imagecreate(113, 16);
		imagecolorallocate($img, 255, 255, 255);
		$textcolor = imagecolorallocate($img, 51, 51, 51);
		imagestring($img, 7, 0, 0, "+65 $str", $textcolor);

		header('Content-type: image/png');
		imagepng($img);
		imagedestroy($img);
	}
	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		//$this->redirect(array("news/index"));
		$this->pageDescription="iLook新加坡,新加坡华语新闻网,新加坡掌上资讯,新加坡掌上论坛";
		$this->pageKeywords="iLook新加坡,新加坡掌上新闻,新加坡掌上论坛";
		
		$bbsTopics = BbsTopic::model()->findAll(" flag='active' or flag = 'featured' order by id desc limit 5 ");
		$bbsTopics2 = BbsTopic::model()->findAll(" flag='active' or flag = 'featured' order by id desc limit 5,5 ");
		
		//不显示【秘密花园】的新闻
		$newsTopics = NewsTopic::model()->findAll("category_id!='2' and (flag='active' or flag = 'featured' ) order by id desc limit 5 ");
		$newsTopics2 = NewsTopic::model()->findAll("category_id!='2' and (flag='active' or flag = 'featured' ) order by id desc limit 5,5 ");
		
		$this->render('index',array(
				"bbsTopics"=>$bbsTopics,
				"newsTopics"=>$newsTopics,
				"bbsTopics2"=>$bbsTopics2,
				"newsTopics2"=>$newsTopics2,
			));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
			echo $error['message'];
			else
			$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login()){
				$this->redirect(Yii::app()->user->returnUrl);
			}
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

	public function actionRegister(){
		$member = new Member();
		if(isset($_POST['Member'])){
			$member->attributes = $_POST['Member'];
			$member->pass = $_POST['Member']['pass'];
			$member->pass_repeat = $_POST['Member']['pass_repeat'];
			if($member->validate()){
				$member->ip = $_SERVER['REMOTE_ADDR'];
				$member->flag = "active";
				$member->pass = md5(Constants::$salt.$member->pass);
				$member->pass_repeat = md5(Constants::$salt.$member->pass_repeat);
				if(!$member->save()){
					$this->render('register',array('member'=>$member));
					return;
				}
				//发送注册通知邮件
//  				$email = Yii::app()->email;
//  				$email->to = $member->email;
//  				$email->subject = 'Welcome to join iWeb.sg';
//  				$email->message = '&#24863;&#35874;&#24744;&#27880;&#20876;&#26032;&#21152;&#22369;&#21517;&#29255;&#32593;&#65292;&#24744;&#30340;&#36134;&#21495;&#20026;&#65306;'.$member->username.'&#12290;&#33509;&#24744;&#20002;&#22833;&#23494;&#30721;&#65292;&#21487;&#20197;&#36890;&#36807;&#30331;&#24405;&#30028;&#38754;&#30340;&#23494;&#30721;&#25214;&#22238;&#21151;&#33021;&#37325;&#35774;&#30331;&#24405;&#23494;&#30721;&#65281;';
//  				$email->send();
				//创建detail
				$detail=new MemberDetails();
				$detail->id=$member->id;
				$detail->save();
				//注册完成后自动登录
				$model=new LoginForm;
				$model->username = $member->username;
				$model->password= $_POST['Member']['pass'];
				$model->login();
				
				$this->redirect(array("site/page","view"=>"register"));
				CApplication::end();
			}else{
				$this->render('register',array('member'=>$member));
				CApplication::end();
			}
		}
		$this->render('register',array('member'=>$member));
	}
	public function actionFindpass(){
		if (!empty($_GET['username'])){
			//查找该用户
			$pk = $_GET['username'];
			$criteria = new CDbCriteria;
			$criteria -> condition = "username='$pk'";
			$criteria -> limit = "1";
			$posts= Member::model()->findAll($criteria);
			if (!empty($posts)){
				$member = new Member();
				foreach($posts as $post){
					$member = $post;
				}
				//查找用户今日申请
				$criteria = new CDbCriteria;
				$criteria -> condition = "member_id='$member->id'";
				$criteria -> limit = "1";
				$requests= Resetpass::model()->findAll($criteria);
				foreach($requests as $request){
					$resetLatest = $request;
				}
				$today = date("Y-m-d");
				if(!empty($resetLatest) && $today==substr($resetLatest->created, 0,10)){
					$error = "您每天只允许发送一次申请，请注意查收邮件，谢谢合作！<br/>如果您有任何疑问，请联系我们的网站管理员！";
					$this->render('findpass',array(
							'error'=>$error,
					));
				}else{
				//创建密码重设链接
				$resetpass = new Resetpass();
				$resetpass->member_id= $member->id;
				$Random = new GetRandom();
				$resetpass->random_path=$Random->generate_random_char('32');
				$resetpass->save();
				//发送注册通知邮件
 				$email = Yii::app()->email;
 				$email->to = $member->email;
 				$email->subject = 'Request to reset password of iLook.sg';
 				$email->message = "&#24744;&#30003;&#35831;&#37325;&#35774;&#24744;&#22312;iweb.sg&#36134;&#25143;".$member->username."&#30340;&#30331;&#38470;&#23494;&#30721;&#35831;&#20351;&#29992;&#22914;&#19979;&#38142;&#25509;&#37325;&#35774;&#24744;&#30340;&#30331;&#24405;&#23494;&#30721;&#65306;www.iweb.sg/site/resetpass/id/".$resetpass->id."/safecode/".$resetpass->random_path; 		
 				$email->send();			
				//转回Acknowledge Page
				$useremail = substr($member->email, 0,strpos($member->email, '@')-3)."***".substr($member->email, strpos($member->email, '@'));
				$this->render('findpass',array(
										'info'=>"一封重设密码的邮件将发送至您的绑定邮箱".$useremail."，请注意查收！"
				));
				}
			}else{
				$this->redirect(array("site/page","view"=>"error"));
			}
		}else{
			$this->render('findpass');
		}
	}
	
	
	public function actionResetpass($id=null, $safecode=null){
		if ($id!=null && $safecode!=null){
			$requestUrl = Resetpass::model()->findByPK($id);
			if(isset($requestUrl)&& $requestUrl->random_path==$safecode){
				//查找用户
				$member = Member::model()->findByPK($requestUrl->member_id);
				//查找申请记录
				$criteria = new CDbCriteria;
				$criteria -> condition = "member_id='$member->id'";
				$criteria -> order ='created desc';
				$criteria -> limit = "1";
				$requests= Resetpass::model()->findAll($criteria);
				//
				$requestLatest = new Resetpass();
				foreach($requests as $request){
					$requestLatest = $request;
				}
				//核实申请链接是否为最新
				if($safecode=="$requestLatest->random_path"){
					$success = null;
					$error = null;
					
					if(!empty($_POST['pass']) && !empty($_POST['pass_repeat'])){
						if($_POST['pass']==$_POST['pass_repeat']){
							$pass = $_POST['pass'];
							$pass_repeat = $_POST['pass_repeat'];
							$member->pass = md5(Constants::$salt.$pass);
							$member->pass_repeat = md5(Constants::$salt.$pass);
							$member->ip = $_SERVER['REMOTE_ADDR'];
							if($member->save()){
								$success ="密码重设成功，请用新密码登陆，谢谢您对本网站的支持！";
								//删除该用户所有重设密码申请
								Resetpass::model()->deleteAll("member_id=$member->id");
								//发送邮件通知
								$email = Yii::app()->email;
								$email->to = $member->email;
								$email->subject = 'Reset password of iWeb.sg Successfully!';
								$email->message = "&#24744;&#24050;&#32463;&#25104;&#21151;&#26356;&#25913;&#24744;&#30340;&#36134;&#25143;&#23494;&#30721;,&#24744;&#30340;&#36134;&#25143;&#20026;&#65306;".$member->username.",&#35831;&#22949;&#21892;&#20445;&#23384;&#24744;&#30340;&#26032;&#23494;&#30721;&#65281;";
								$email->send();
							}else{
								$error = "系统出错了，请稍后再试；若扔存在问题，请与联系我们的网站管理员联系！";
							}
						}
						else{
							$error = "两次输入密码不一致！";
						}
					}
					$this->render('resetpass',array(
												'id'=>$id,
												'username'=>$member->username,
												'safecode'=>$safecode,
												'success'=>$success,
												'error'=>$error,
					));
					CApplication::end();
				}
			}
		}
		$this->redirect(array("site/page","view"=>"error"));
	}	
}